import groovy.json.JsonSlurper

/**
 * Created by hzhlu on 2017-02-16.
 */


def groovy = "groovy"
println "hello ${groovy}"
println "${groovy[0..3]}"
println "${groovy[-3..-1]}"
println 'hello ${groovy}'
println groovy.center(50, "=*")

def nullObj = "null##11"
println "safe null: ${nullObj?.toString()}"
nullObj = null
println "safe null: ${nullObj?.toString()}"

def map = [:]
map = [k1: 123, k2: "111", k3: "value3", k4: new Date()]
println "map: ${map['k4']}"
String jsonStr = groovy.json.JsonOutput.toJson(map)
println "obj to jsonStr: map: ${map}  ==> ${jsonStr}"
print "func1（null）: "; println func1(null)
println "func1: " + func1(map)
println "after func1 map: " + map

//        println new MyGroovyClass().func2(map)


def jsonObj = new JsonSlurper().parseText(jsonStr)
println "jsonStr to obj: ${jsonObj}"

def list = [1, 2, 3, 4, '555', new Date()]


try {
    /* ... */
} catch (IOException | NullPointerException e) {
    /* one block to handle 2 exceptions */
}
//        def value = "groovy"
//        def value = 31
//        def value = 2
def value = '0400/12'
switch (value) {
    case 'groovy':
        println "gro!"
        break;
    case 1..10:
        println "123"
        break;
    case [31, 42, 53, 64]:
        println "数组"
        break;
    case ~/0400\/\d{2}/:
        println "Reg表达式"
        break;
    default:
        println("没找到")
}

// 写文件
File file = new File("filename");
println "write to file ==>  ${file.absolutePath}"
def writer = file.newPrintWriter("UTF-8");
//循环
3.times { it ->
    writer << "第 ${it} 行|v1|v2|" + System.currentTimeMillis() << "\n"
}
5.upto(7) { it ->
    writer << "第 ${it} 行|v3|v4|" + System.currentTimeMillis() << "\n"
}

(9..11).each { it ->
    writer << "第 ${it} 行|v5|v6|" + System.currentTimeMillis() << "\n"
}



writer.flush()
writer.close()

// 读文件
println("读文件1".padLeft(50, "="))
file.readLines().each { line ->
    println line
}

println("读文件2".padRight(50, "+"))
file.splitEachLine "\\|", 'UTF-8', { line ->
    println line
    line.each {
        println it
    }
}


static func1(map) {
    println map
    map?.kx = 112233
}

def func2() {
    println map
    map?.ky = 'ffvvdd'

}